/**
 * 融资服务业务实现类 - 处理融资申请的核心业务逻辑和流程管理
 *
 * 开发人员：马勇俐
 * 开发时间：2025-11-16 至 2025-11-20
 * 模块职责：实现融资申请的创建、审批、状态管理等业务逻辑，与AI分析服务协同工作
 *
 * 技术要点：
 * - 融资申请全生命周期管理
 * - 融资评分算法和评估机制
 * - 多租户数据隔离和权限控制
 * - 业务规则验证和异常处理
 * - 与AI分析服务的集成调用
 *
 * 开发故事：负责融资服务的核心业务逻辑实现，与融资控制器和AI分析服务深度集成，确保融资申请流程的完整性和准确性。
 */
package com.pbl.service.impl;

import com.pbl.common.enums.FinancingRequestStatus;
import com.pbl.common.exception.BizException;
import com.pbl.entity.Enterprise;
import com.pbl.entity.FinancingRequest;
import com.pbl.entity.User;
import com.pbl.repository.EnterpriseRepository;
import com.pbl.repository.FinancingRequestRepository;
import com.pbl.repository.UserRepository;
import com.pbl.service.FinancingAiService;
import com.pbl.service.FinancingService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FinancingServiceImpl implements FinancingService {

    private final FinancingRequestRepository financingRequestRepository;
    private final EnterpriseRepository enterpriseRepository;
    private final UserRepository userRepository;
    private final JdbcTemplate jdbcTemplate;
    private final FinancingAiService financingAiService;

    public FinancingServiceImpl(FinancingRequestRepository financingRequestRepository, 
                              EnterpriseRepository enterpriseRepository, 
                              UserRepository userRepository,
                              JdbcTemplate jdbcTemplate,
                              FinancingAiService financingAiService) {
        this.financingRequestRepository = financingRequestRepository;
        this.enterpriseRepository = enterpriseRepository;
        this.userRepository = userRepository;
        this.jdbcTemplate = jdbcTemplate;
        this.financingAiService = financingAiService;
    }

    @Override
    public FinancingRequest create(Long enterpriseId, Long userId, BigDecimal requestedAmount, String purpose) {
        Enterprise ent = enterpriseRepository.findById(enterpriseId).orElseThrow(() -> new BizException(404, "企业不存在"));
        User user = userRepository.findById(userId).orElse(null);
        FinancingRequest fr = new FinancingRequest();
        fr.setEnterprise(ent);
        fr.setApplicantUser(user);
        fr.setRequestedAmount(requestedAmount);
        fr.setPurpose(purpose);
        fr.setStatus(FinancingRequestStatus.DRAFT);
        return financingRequestRepository.save(fr);
    }

    @Override
    public FinancingRequest updateScore(Long id, BigDecimal score) {
        FinancingRequest fr = get(id);
        fr.setScore(score);
        fr.setStatus(FinancingRequestStatus.EVALUATED);
        return financingRequestRepository.save(fr);
    }

    @Override
    public FinancingRequest get(Long id) {
        return financingRequestRepository.findById(id).orElseThrow(() -> new BizException(404, "融资申请不存在"));
    }

    @Override
    public List<FinancingRequest> listByEnterprise(Long enterpriseId) {
        return financingRequestRepository.findAll().stream()
            .filter(fr -> fr.getEnterprise().getId().equals(enterpriseId))
            .toList();
    }

    @Override
    public Map<String, Object> evaluateFinancingRequest(Long requestId) {
        // 使用AI服务进行真实分析
        return financingAiService.analyzeFinancingRequest(requestId);
    }

    @Override
    public List<Map<String, Object>> getFinancingChannels(Long enterpriseId) {
        return jdbcTemplate.queryForList(
            "SELECT * FROM financing_channels WHERE enterprise_id = ? AND status = 1 ORDER BY interest_rate ASC",
            enterpriseId
        );
    }

    @Override
    public Map<String, Object> getFinancialHealth(Long enterpriseId) {
        // 使用AI服务进行真实分析
        return financingAiService.analyzeFinancialHealth(enterpriseId);
    }

    @Override
    public Map<String, Object> calculateFinancingCost(Long requestId, String channelType) {
        FinancingRequest request = get(requestId);
        
        Map<String, Object> channel = jdbcTemplate.queryForMap(
            "SELECT * FROM financing_channels WHERE channel_type = ? AND enterprise_id = ? LIMIT 1",
            channelType, request.getEnterprise().getId()
        );
        
        Map<String, Object> cost = new HashMap<>();
        cost.put("requestedAmount", request.getRequestedAmount());
        cost.put("channelType", channelType);
        cost.put("channelName", channel.get("channel_name"));
        
        BigDecimal interestRate = (BigDecimal) channel.get("interest_rate");
        Integer termMonths = (Integer) channel.get("term_months");
        
        if (interestRate != null && termMonths != null) {
            // 计算总利息
            BigDecimal totalInterest = request.getRequestedAmount()
                .multiply(interestRate)
                .multiply(BigDecimal.valueOf(termMonths))
                .divide(BigDecimal.valueOf(12), 2, RoundingMode.HALF_UP);
            
            cost.put("interestRate", interestRate.multiply(BigDecimal.valueOf(100)));
            cost.put("termMonths", termMonths);
            cost.put("totalInterest", totalInterest);
            cost.put("totalCost", request.getRequestedAmount().add(totalInterest));
            cost.put("monthlyPayment", request.getRequestedAmount()
                .add(totalInterest)
                .divide(BigDecimal.valueOf(termMonths), 2, RoundingMode.HALF_UP));
        }
        
        return cost;
    }

    @Override
    public Map<String, Object> getFinancingRecommendations(Long enterpriseId) {
        // 获取财务健康状况
        Map<String, Object> health = getFinancialHealth(enterpriseId);
        
        // 简单返回健康状况和融资时机
        Map<String, Object> recommendations = new HashMap<>();
        recommendations.put("health", health);
        recommendations.put("timing", health.get("timing"));
        
        return recommendations;
    }

}
